package com.test.zk;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
    public static void main(String[] args) {
        Socket socket = null;// 1.建立一个与服务端之间的连接
        OutputStream output = null;// 用于向别人发消息
        InputStream input = null;// 用于读取别人发过来的消息
        try {
            socket = new Socket("127.0.0.1", 8888);
            // 2.将需要发送的数据写入到网络中，注意：包含了两个流：InputStream和OutputStream
            output = socket.getOutputStream();//客户端对服务端说
            output.write("hello你好吗?".getBytes());// 3.写入
            output.flush();
            // 4.收取服务端发送来的消息 new BufferedInputStream(socket.getInputStream());
            input = socket.getInputStream();//读服务端的响应
            byte[] arr = new byte[1024];
            int len = input.read(arr);
            String message = new String(arr, 0, len);
            System.out.println("来自服务端的回复：" + message);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
